<?php
/**
 * Created by PhpStorm.
 * User: MI
 * Date: 2018/11/7
 * Time: 14:18
 */

namespace App\Http\Controllers\API\User;


use App\Http\Controllers\Controller;
use App\Http\Resources\CourseResource;
use App\Models\Course;
use App\Models\Lesson;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CourseController extends Controller
{
    /**
     * CourseController constructor.
     */
    public function __construct()
    {

    }

    /**
     * 获取本州课程
     *
     */
    public function getUserLessonsCalendar()
    {
        $user = \Auth::user();
        $lessons = Lesson::query()->whereHas('course.schoolManager', function ($query) use ($user) {
            $query->where('schools.id', $user->student->school_id);
        })->orderBy('start_time')
            ->get();
        $result = [];
        foreach ($lessons as $key => $item) {
            $day = Carbon::parse($item->start_time);
            $date = $day->toDateString();
            $items['datetime'] = sprintf("%02d", $day->hour) . ':' . sprintf("%02d", $day->minute);
            $items['title'] = $item->name;
            $result[$date]['date'] = $date;
            $result[$date]['items'][] = $items;
        }
        return array_values($result);
    }

    /**
     * 获取所有课程
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function getUserCourses(Request $request)
    {
        $date = $request->get('is_onTime');
        $user = \Auth::user();
        $courses = Course::with(['lessons'])
            ->whereHas('schoolManager', function ($query) use ($user) {
                $query->where('schools.id', $user->student->school_id);
            })
            ->when($date,function ($query){
                $query->whereHas('lessons', function ($q){
                    $q->whereDate('start_time', date('Y-m-d', time()));
                });
            })
            ->get();
        return CourseResource::collection($courses);
    }


}